<?php

namespace app\base\model;

use app\common\model\Base;
use think\Cache;

class User extends Base {
  const cacheTag = 'user';
  protected $name = 'base_user';
  protected $auto = ['role_id'];

  public function initialize() {
    parent::initialize();
  }

  protected static function init() {
    $tag = User::cacheTag;
    User::afterWrite(function ($data) use ($tag) {
      Cache::clear($tag);
    });
    User::afterDelete(function ($data) use ($tag) {
      Cache::clear($tag);
    });
  }


  /**
   * @param $value
   * @param $data
   * @return mixed
   * 自动返回status字符串状态
   */

  public function getStatusTextAttr($value, $data) {
    $status = [-1 => '删除',
               0  => '禁用',
               1  => '启用',
               2  => '待审核'];

    return $status[ $data['status'] ];
  }

  public function getSexTextAttr($value, $data) {
    $sexArr = config('sexArr');

    return $sexArr[ $data['sex'] ];
  }

  public function getCommitmentTextAttr($value, $data) {
    $status = ['未签订',
               '已签订'];

    return $status[ $data['commitment'] ];
  }

  /**
   * @param $value
   * @return int
   * 自动填充角色
   */

  public function setRoleIdAttr($value) {
    $c = request()->controller();

    return $c == 'Teacher' ? 2 : 3;
  }

  //
  public function editUser($form, $id) {
    $data = $form;
    try {
      $r = $this->allowField(TRUE)->save($data, ['id' => $id]);
    } catch (\Exception $e) {
      return (lang('fail') . $e->getMessage());
    }
    if ($r === FALSE) {
      return (lang('fail') . $this->getError());
    }
    cmf_log('修改用户资料', $id, $data);

    return TRUE;


  }

  public function addUser($form) {
    $data = $form;
    $data['salt'] = rand(100000, 999999);
    $defPw=config('system')['default_password'];
    $data['password'] = $this->createPassword($defPw, $data['salt']);
    try {
      $r = $this->allowField(TRUE)->save($data);
    } catch (\Exception $e) {
      return (lang('fail') . $e->getMessage());
    }
    if ($r === FALSE) {
      return (lang('fail') . $this->getError());
    }
    cmf_log('新增用户资料', $this->id , $data);
    return TRUE;
  }

  public function getUserInfo($uid, $fields = NULL) {
    $map = ['id' => $uid];
    if ($fields === NULL) {
      $value = $this->where($map)->find();
    } else {
      $value = $this->where($map)->field($fields)->find();
    }

    return $value;
  }

  public function getUserInfoByName($username, $fields = NULL) {
    $map = ['username' => $username];
    if ($fields === NULL) {
      $value = $this->where($map)->find();
    } else {
      $value = $this->where($map)->field($fields)->find();
    }

    return $value;
  }

  public function checkPassword($uid, $passwordStr) {
    $userInfo = $this->getUserInfo($uid, 'password,salt');
    $createPassword = $this->createPassword($passwordStr, $userInfo['salt']);

    return $createPassword == $userInfo['password'];
  }

  /**
   * 锁定用户屏幕
   * @param $uid
   * @return false|int
   */

  public function lockUser($uid) {
    $map = ['id' => $uid];
    $data = ['lock' => 1];

    return $this->save($data, $map);
  }

  public function createPassword($password, $salt) {
    return md5(sha1($password) . $salt);
  }

  public function getTeachers($status = NULL) {
    return self::where('role_id', 2)->column('realname', 'id');
  }

  /**
   * 获取补考名单
   */
  public function getResit() {
    $map = ['role_id'    => 3,
            'exam_times' => ['between',
                             [1,
                              3]],
            'is_pass'    => 0,];

    return self::where($map)
      ->alias('u')
      ->join('__CLASS__ c', 'c.id=u.class_id', 'left')
      ->field('u.*,c.title as class_title')
      ->paginate();
  }


}
